package com.lifeverse.repository;

import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.ConsciousnessLevel;
import com.lifeverse.entity.enums.LifeEntityStatus;
import com.lifeverse.entity.enums.LifeEntityType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 生命体数据访问接口
 */
@Repository
public interface LifeEntityRepository extends JpaRepository<LifeEntity, Long>, JpaSpecificationExecutor<LifeEntity> {
    
    /**
     * 根据名称查找生命体
     */
    Optional<LifeEntity> findByNameAndDeletedFalse(String name);
    
    /**
     * 根据类型查找生命体
     */
    List<LifeEntity> findByTypeAndDeletedFalse(LifeEntityType type);
    
    /**
     * 根据状态查找生命体
     */
    List<LifeEntity> findByStatusAndDeletedFalse(LifeEntityStatus status);
    
    /**
     * 根据意识水平查找生命体
     */
    List<LifeEntity> findByConsciousnessLevelAndDeletedFalse(ConsciousnessLevel consciousnessLevel);
    
    /**
     * 查找活跃的生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.status IN :activeStatuses AND le.deleted = false")
    List<LifeEntity> findActiveEntities(@Param("activeStatuses") List<LifeEntityStatus> activeStatuses);
    
    /**
     * 根据能量水平范围查找生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.energyLevel BETWEEN :minEnergy AND :maxEnergy AND le.deleted = false")
    List<LifeEntity> findByEnergyLevelBetween(@Param("minEnergy") BigDecimal minEnergy, @Param("maxEnergy") BigDecimal maxEnergy);
    
    /**
     * 根据健康度范围查找生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.healthScore BETWEEN :minHealth AND :maxHealth AND le.deleted = false")
    List<LifeEntity> findByHealthScoreBetween(@Param("minHealth") BigDecimal minHealth, @Param("maxHealth") BigDecimal maxHealth);
    
    /**
     * 查找最近活跃的生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.lastActiveAt >= :since AND le.deleted = false ORDER BY le.lastActiveAt DESC")
    List<LifeEntity> findRecentlyActive(@Param("since") LocalDateTime since);
    
    /**
     * 查找需要进化的生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.wisdomScore >= :minWisdom AND le.consciousnessLevel != 'TRANSCENDENT' AND le.deleted = false")
    List<LifeEntity> findEntitiesReadyForEvolution(@Param("minWisdom") BigDecimal minWisdom);
    
    /**
     * 根据父生命体ID查找子生命体
     */
    List<LifeEntity> findByParentIdAndDeletedFalse(Long parentId);
    
    /**
     * 统计各类型生命体数量
     */
    @Query("SELECT le.type, COUNT(le) FROM LifeEntity le WHERE le.deleted = false GROUP BY le.type")
    List<Object[]> countByType();
    
    /**
     * 统计各状态生命体数量
     */
    @Query("SELECT le.status, COUNT(le) FROM LifeEntity le WHERE le.deleted = false GROUP BY le.status")
    List<Object[]> countByStatus();
    
    /**
     * 统计各意识水平生命体数量
     */
    @Query("SELECT le.consciousnessLevel, COUNT(le) FROM LifeEntity le WHERE le.deleted = false GROUP BY le.consciousnessLevel")
    List<Object[]> countByConsciousnessLevel();
    
    /**
     * 查找高智慧生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.wisdomScore >= :minWisdom AND le.deleted = false ORDER BY le.wisdomScore DESC")
    Page<LifeEntity> findHighWisdomEntities(@Param("minWisdom") BigDecimal minWisdom, Pageable pageable);
    
    /**
     * 查找高创造力生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.creativityScore >= :minCreativity AND le.deleted = false ORDER BY le.creativityScore DESC")
    Page<LifeEntity> findHighCreativityEntities(@Param("minCreativity") BigDecimal minCreativity, Pageable pageable);
    
    /**
     * 查找协作能力强的生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.collaborationScore >= :minCollaboration AND le.deleted = false ORDER BY le.collaborationScore DESC")
    Page<LifeEntity> findHighCollaborationEntities(@Param("minCollaboration") BigDecimal minCollaboration, Pageable pageable);
    
    /**
     * 查找长时间未活跃的生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.lastActiveAt < :threshold AND le.status != 'TERMINATED' AND le.deleted = false")
    List<LifeEntity> findInactiveEntities(@Param("threshold") LocalDateTime threshold);
    
    /**
     * 查找需要关注的生命体（健康度或能量低）
     */
    @Query("SELECT le FROM LifeEntity le WHERE (le.healthScore < :healthThreshold OR le.energyLevel < :energyThreshold) AND le.deleted = false")
    List<LifeEntity> findEntitiesNeedingAttention(@Param("healthThreshold") BigDecimal healthThreshold, @Param("energyThreshold") BigDecimal energyThreshold);
    
    /**
     * 根据名称模糊查询
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.name LIKE %:keyword% AND le.deleted = false")
    Page<LifeEntity> findByNameContaining(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 查找最近创建的生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.birthTime >= :since AND le.deleted = false ORDER BY le.birthTime DESC")
    List<LifeEntity> findRecentlyBorn(@Param("since") LocalDateTime since);
    
    /**
     * 查找最近进化的生命体
     */
    @Query("SELECT le FROM LifeEntity le WHERE le.lastEvolutionAt >= :since AND le.deleted = false ORDER BY le.lastEvolutionAt DESC")
    List<LifeEntity> findRecentlyEvolved(@Param("since") LocalDateTime since);
    
    /**
     * 获取生命体的平均年龄（天数）
     */
    @Query("SELECT AVG(DATEDIFF(CURRENT_DATE, le.birthTime)) FROM LifeEntity le WHERE le.deleted = false")
    Double getAverageAgeInDays();
    
    /**
     * 获取生命体的平均智慧值
     */
    @Query("SELECT AVG(le.wisdomScore) FROM LifeEntity le WHERE le.deleted = false")
    BigDecimal getAverageWisdomScore();
    
    /**
     * 获取生命体的平均创造力值
     */
    @Query("SELECT AVG(le.creativityScore) FROM LifeEntity le WHERE le.deleted = false")
    BigDecimal getAverageCreativityScore();
    
    /**
     * 获取生命体的平均协作能力值
     */
    @Query("SELECT AVG(le.collaborationScore) FROM LifeEntity le WHERE le.deleted = false")
    BigDecimal getAverageCollaborationScore();
}